/**
 * Created by Ysssssss on 2021/5/3.
 */

import React, { PureComponent } from 'react'
import {DesignTemplateContext} from "@pages/shoppingMall/ShoppingMallDesignDetailPage";
import ShoppingMallPreviewShareIcon from "@components/shoppingMall/ShoppingMallPreviewShareIcon";
import {Col, Radio, Row, Checkbox} from "antd";
import ImageUpload from "@common/presentational/ImageUpload";
import {CustomizeDndProvider, DraggableDiv} from "@common/presentational/DndSort";
import {moveToNewIndex} from "@utils/arrayHelper";
import ParamsInput from "@common/presentational/ParamsInput";
import {HomeOutlined, RightOutlined} from "@ant-design/icons";
import {getHistoryMatchParams} from "@utils/setUrlQuery";
import {withRouter} from "react-router-dom";
import BilinIcon from "@common/presentational/BilinIcon";

let menuList = ['orderList', 'address', 'service']

let menuMap = {
    'orderList': '订单列表',
    'address': '地址管理',
    'service': '客服电话'
}

let menuIcon = {
    orderList: 'design-order',
    address: 'design-address',
    service: 'design-support',
}

@withRouter
class OwnerDesign extends PureComponent {
    static contextType = DesignTemplateContext;

    constructor(props, context) {
        super(props, context);
        const { templateInfo, subNav } = context
        const { owner } = templateInfo
        this.state = {
            customizeBackground: !!owner.backgroundSrc,
            setServicePhone: false
        }

        const { platformId } = getHistoryMatchParams(props)
        if (!subNav.includes('owner')) {
            props.history.replace(`/shopping-mall/design/${platformId}/detail`)
        }
    }

    showSetServicePhone () {
        this.setState({
            setServicePhone: true
        })
    }

    handleCustomizeBackgroundChange (e) {
        this.setState({
            customizeBackground: e.target.value
        })
    }

    onValueChange (key, value) {
        const { onChange, templateInfo } = this.context
        if (key === 'serviceNumber') {
            this.setState({
                setServicePhone: false
            }, () => {
                onChange && onChange('owner', {
                    ...templateInfo.owner,
                    [key]: value,
                })
            })
        } else {
            onChange && onChange('owner', {
                ...templateInfo.owner,
                [key]: value,
            })
        }
    }

    onTargetChange (key, e) {
        const { onChange, templateInfo } = this.context
        onChange && onChange('owner', {
            ...templateInfo.owner,
            [key]: e.target.value
        })
    }

    handleMenuChange (navType, e) {
        const { onChange, templateInfo } = this.context
        let checked = e.target.checked
        if (checked) {
            onChange && onChange('owner', {
                ...templateInfo.owner,
                menuList: [
                    ...templateInfo.owner.menuList,
                    {
                        navType,
                        name: menuMap[navType]
                    }
                ]
            })
        } else {
            onChange && onChange('owner', {
                ...templateInfo.owner,
                menuList: [
                    ...templateInfo.owner.menuList.filter(menu => menu.navType !== navType)
                ]
            })
        }
    }

    sortList (dragId, hoverId) {
        const { onChange, templateInfo } = this.context
        const { owner } = templateInfo
        let dragIndex = 0
        let hoverIndex = 0
        owner.menuList.forEach((item, i) => {
            if(item.navType === dragId) {
                dragIndex = i
            }
            if(item.navType === hoverId) {
                hoverIndex = i
            }
        })
        onChange && onChange('owner', {
            ...templateInfo.owner,
            menuList: moveToNewIndex(owner.menuList, dragIndex, hoverIndex)
        })
    }

    render () {
        const { customizeBackground, setServicePhone } = this.state
        const { templateInfo, bizType, pStoreId } = this.context
        const { owner } = templateInfo
        let menuTypeSet = []
        return (
            <>
                <div className="preview-container">
                    <div className="preview-reality">
                        <ShoppingMallPreviewShareIcon />
                        <div className="owner-preview">
                            <div className='owner-base  theme-ft-normal'
                                 style={ customizeBackground && owner.backgroundSrc ? {
                                     backgroundImage: `url(${owner.backgroundSrc})`,
                                     backgroundRepeat:'no-repeat',
                                     backgroundSize: "cover",
                                 } : {}} >
                                <div className='user-base-info'>
                                    <div className='user-info' >
                                        <div className='left-box'>
                                            <img src={require("@assets/image/profile_photo.png")} alt="" className="person-image"/>
                                            <img src={require("@assets/image/svip.png")} alt="" className="svip-image"/>
                                            <span className='name'>用户名</span>
                                            <span className='phone'>135****5678 ></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className={`user-card-info theme-ft-normal ${owner.backgroundSrc ? 'custom-bg' : 'theme-bg-linear-gradient'}`}>
                                <div className='money-info' >
                                    <div className='item'>
                                        <span className='num' >323.5</span>
                                        <span className='info'>余额（元）</span>
                                    </div>
                                    <div className='item'>
                                        <span className='num'>2</span>
                                        <span className='info'>优惠券</span>
                                    </div>
                                    <div className='item'>
                                        <span className='num'>3000</span>
                                        <span className='info'>积分</span>
                                    </div>
                                </div>
                                { owner.isShowFullCard ?
                                    <div className="member-card-image-box">
                                        <img src={require("@assets/image/member_card.png")} alt="" className="member-card-image"/>
                                    </div> :
                                    <div className="member-card-image-box simple-card">
                                        <img src={require("@assets/image/mini_membercard.png")} alt="" className="member-card-image"/>
                                    </div>
                                }
                            </div>
                            <div className="menu-list">
                                { owner.menuList.map(menu => (
                                    <div className="pd-16 flex-row-between" key={menu.navType}>
                                        <div>
                                            <BilinIcon type={menuIcon[menu.navType]}/>
                                            <span className="mgl-8">{ menu.name }</span>
                                        </div>
                                        <RightOutlined className="ft-12 flex-vertical-center"/>
                                    </div>
                                )) }
                            </div>
                        </div>
                    </div>
                </div>
                <div className="operation-container ft-clr-d">
                    <div className="ft-16">我的</div>
                    <div className="ft-12 ft-clr-ml pdb-16 bdb-l">配置我的页面的文案</div>
                    <div className="ft-14 ft-clr-ml mgt-24">基础信息</div>
                    <Row className="mgt-16">
                        <Col span={6}>背景：</Col>
                        <Col span={18}>
                            <Radio.Group onChange={this.handleCustomizeBackgroundChange.bind(this)} value={customizeBackground}>
                                <Radio value={false}>默认</Radio>
                                <Radio value={true}>自定义</Radio>
                            </Radio.Group>
                        </Col>
                    </Row>
                    { customizeBackground ? (
                        <Row className="mgt-16">
                            <Col span={6}/>
                            <Col span={18}>
                                <ImageUpload
                                    value={owner.backgroundSrc}
                                    onChange={this.onValueChange.bind(this, 'backgroundSrc')}
                                    accept='image/png, image/jpeg, image/jpg'
                                    maxFileSize="1m"
                                    uploadIntro={(
                                        <div className="ft-12 ft-clr-ml mgl-16" style={{width: '160px'}}>
                                            支持PNG、JPG格式，不超过1M，建议尺寸750*250PX
                                        </div>
                                    )}
                                />
                            </Col>
                        </Row>
                    ) : null }
                    <Row className="mgt-24">
                        <Col span={6}>会员样式：</Col>
                        <Col span={18}>
                            <Radio.Group onChange={this.onTargetChange.bind(this, 'isShowFullCard')} value={owner.isShowFullCard}>
                                <Radio value={true}>完整卡片</Radio>
                                <Radio value={false}>简化卡片</Radio>
                            </Radio.Group>
                        </Col>
                    </Row>
                    <div className="ft-14 ft-clr-ml mgt-36">常用功能</div>
                    <div className="mgt-24 flex-row-between">
                        <span className="ft-14 ft-clr-d">设置菜单：</span>
                        <span className="ft-12 ft-clr-ml">可拖动菜单调整顺序</span>
                    </div>
                    <CustomizeDndProvider>
                        { owner.menuList.map(menu => {
                            menuTypeSet.push(menu.navType)
                            return (
                                <DraggableDiv
                                    key={menu.navType}
                                    id={menu.navType}
                                    type="menuList"
                                    moveItemFunc={this.sortList.bind(this)}
                                >
                                    <div key={menu.navType} className="mgt-16 pdl-16 pdr-16 operation-block-bg flex-row-between">
                                        <Checkbox className="pdt-16 pdb-16" checked={true} onChange={this.handleMenuChange.bind(this, menu.navType)}>
                                            <span className="mgl-16">{menu.name}</span>
                                        </Checkbox>
                                        { menu.navType === 'service' ? (
                                            <SetServicePhoneModule
                                                value={owner.serviceNumber}
                                                showSet={this.showSetServicePhone.bind(this)}
                                                active={setServicePhone}
                                                onChange={this.onValueChange.bind(this, 'serviceNumber')}
                                            />
                                        ) : null }
                                    </div>
                                </DraggableDiv>
                            )
                        }) }
                    </CustomizeDndProvider>
                    { menuList.map(navType => menuTypeSet.includes(navType) ? null : (
                        <div key={navType} className="mgt-16 pdl-16 pdr-16 operation-block-bg flex-row-between">
                            <Checkbox className="pdt-16 pdb-16" checked={false} onChange={this.handleMenuChange.bind(this, navType)}>
                                <span className="mgl-16">{menuMap[navType]}</span>
                            </Checkbox>
                            { navType === 'service' && !(pStoreId && bizType !== 'agent') ? (
                                <SetServicePhoneModule
                                    value={owner.serviceNumber}
                                    showSet={this.showSetServicePhone.bind(this)}
                                    active={setServicePhone}
                                    onChange={this.onValueChange.bind(this, 'serviceNumber')}
                                />
                            ) : null }
                        </div>
                    )) }
                </div>
            </>
        )
    }
}

export default OwnerDesign

const SetServicePhoneModule = props => {
    const { value, showSet, active, onChange } = props

    return active ? (
        <ParamsInput value={value} alwaysChange autoFocus onChange={onChange} style={{width: '150px'}}/>
    ) : (
        value ? (
            <span className="cur-poi" onClick={showSet}>{ value }</span>
        ) : (
            <span className="cur-poi clr-green" onClick={showSet}>去设置</span>
        )
    )
}